package com.dyh.quickdemozwei.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @Author: yhdong
 * @Date: 2021/12/1 16:40
 */
public class HttpClinetCallKernel {

    static Charset charset = StandardCharsets.UTF_8;

    @SneakyThrows
    public static String postKernel(String url, HttpClient client, Map<String,String> headsMap, Map<String,Object> bodyMap, Function<Map<String,Object>, HttpEntity> bodyMapper){
        HttpPost httpPost = new HttpPost(url);
        addHeads(httpPost,headsMap);
        if (bodyMap!=null){
            HttpEntity httpEntity = bodyMapper.apply(bodyMap);
            httpPost.setEntity(httpEntity);
        }

        HttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity,charset);

        return result;
    }

    @SneakyThrows
    public static String getKernel(String url, HttpClient client, Map<String, String> headsMap, Map<String, String> queryMap){


        if (headsMap!=null){
            url = url+trans2QueryStr(queryMap);
        }
        HttpGet httpGet = new HttpGet(url);
        addHeads(httpGet,headsMap);


        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity,charset);
        return result;
    }

    @SneakyThrows
    public static String putKernel(String url, HttpClient client, Map<String,String> headsMap,
                                   Map<String,Object> body){
        HttpPut httpPut = new HttpPut(url);
        addHeads(httpPut,headsMap);


        httpPut.setEntity(HttpClinetCallKernel.map2Js(body));

        HttpResponse response = client.execute(httpPut);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity,charset);
        return result;
    }

    @SneakyThrows
    public static String deleteKernel(String url, HttpClient client, Map<String, String> headsMap, Map<String, String> queryMap){

        if (queryMap!=null){
            url = url+trans2QueryStr(queryMap);
        }
        HttpDelete httpDelete = new HttpDelete(url);
        addHeads(httpDelete,headsMap);

        /*
        String.valueOf(response.getStatusLine().getStatusCode()).startsWith("2")
        2 开头 成功
         String result = EntityUtils.toString(entity,charset);报错
        */

        HttpResponse response = client.execute(httpDelete);
        HttpEntity entity = response.getEntity();
       // String result = EntityUtils.toString(entity,charset);
        return "{}";
    }

    public static void addHeads(HttpRequestBase mono, Map<String,String> headsMap){

        if (headsMap!=null){
            for (Map.Entry<String, String> entry : headsMap.entrySet()) {
                mono.addHeader(entry.getKey(),entry.getValue());
            }
        }
    }

    public static HttpEntity map2NameValuePair(Map<String,Object> bodyMap){
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        for (Map.Entry<String, Object> entry : bodyMap.entrySet()) {
            String val = null;
            if (entry.getValue() instanceof  String)
                val = entry.getValue().toString();
            else
                val = JSON.toJSONString(entry.getValue());
            nameValuePairs.add(new BasicNameValuePair(entry.getKey(),val));
        }
        return new UrlEncodedFormEntity(nameValuePairs, charset);
    }

    public static HttpEntity map2Js(Map<String,Object> bodyMap){
        return new StringEntity(JSONObject.toJSONString(bodyMap),charset);
    }

    public static String trans2QueryStr(Map<String,String> param){
        StringBuilder result = new StringBuilder();

        boolean first = true;
        for (Map.Entry<String, String> entry : param.entrySet()) {
            if (first){
                result.append("?");
                first = false;
            }
            else {
                result.append("&");
            }
            result.append(entry.getKey()).append("=").append(entry.getValue());
        }

        return result.toString();
    }

//    public static void main(String[] args) {
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("a","a1");
//        jsonObject.put("b","b1");
//
//        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
//            System.out.println(entry.getKey()+":"+entry.getValue());
//        }
//
//        System.out.println();
//    }


}
